<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
      <uni-forms-item name="user_id" label="用户" required>
        <uni-data-select
        		 collection="uni-id-users"
        		 field="_id as value, nickname as text"
        		 v-model="formData.user_id"
         />
      </uni-forms-item>
      <uni-forms-item name="type" label="角色层级" required>
        <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata"  @change="changeType"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="parent_id" label="上级">
		<uni-data-select
				 collection="uni-id-users"
				 field="_id as value, nickname as text"
				 v-model="formData.parent_id"
		 />
      </uni-forms-item>
      <uni-forms-item name="description" label="备注">
        <uni-easyinput placeholder="备注" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-permission.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-permission';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "user_id": "",
        "type": "",
        "parent_id": "",
        "status": true,
        "description": "",
        "create_date": null,
        "last_modify_date": null
      }
      return {
		userOptions:[],
        formData,
        formOptions: {
          "type_localdata": [
            {
              "text": "普通游客",
              "value": 0
            },{
              "text": "业务员",
              "value": 1
            },
            {
              "text": "团队主管",
              "value": 2
            },
            {
              "text": "门店店长",
              "value": 3
            },
            {
              "text": "区域代理",
              "value": 4
            },
            {
              "text": "总经理",
              "value": 5
            },
            {
              "text": "部门总监",
              "value": 6
            },
            {
              "text": "总管理员",
              "value": 7
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      async changeType(e){
		  // let users= await db.collection('uni-id-users').field('username,nickname').get()
		  // let permissions= await db.collection('mydb-permission').where({type:e.detail.value+1}).field('user_id').get()
		  // users=users.result.data
		  // permissions=permissions.result.data.map((item)=>item.user_id)
		  // this.userOptions=users.filter((item)=> permissions.includes(item._id)).map((op)=>{
			 //  return {
				//   text:op.username || op.nickname,
				//   value:op._id
			 //  }
		  // })
	  },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
